﻿using Newtonsoft.Json;
using PCS.DTO;
using RabbitMQ.Client;
using RabbitMQ.Client.Events;
using RabbitMQ.Client.Exceptions;
using RabbitMQShare;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;
using System.Windows;

namespace PCS
{
    public class Consumer
    {
        public static IConnection _connection;
        public static IModel _channel;
        public static void ConsumerMessage(string queueName)
        {
            try
            {
                if (_connection == null) return;
                _channel.BasicQos(0, 1, false);
                //channel.ExchangeDeclare("Exchange", "direct");
                //_channel.QueueDeclare(queueName, false, false, false);
                //channel.QueueBind(queueName, "Exchange", "RouteA");
                var consumer = new EventingBasicConsumer(_channel);
                consumer.Received += (model, ea) =>
                {
                    //The QueueA is always successful.
                    string message = Encoding.UTF8.GetString(ea.Body.ToArray());//接收消息
                    TaskInfoDTO taskInfo = JsonConvert.DeserializeObject<TaskInfoDTO>(message);
                    // 模拟处理任务，延时15秒
                    Thread.Sleep(5000);
                    try
                    {
                        // 判断任务是否存在
                        if (RabbitMQUtil._keys.Count > 0 && RabbitMQUtil._keys.Contains(taskInfo.Task_Id))
                        {
                            //  模拟数据库修改任务状态
                            TaskInfoDTO task=null;
                            foreach (var item in MainWindow.data.TaskInfos)
                            {
                                if (item.Task_Id == taskInfo.Task_Id)
                                {
                                    task = item;
                                    break;
                                }
                            }
                            if (task != null)
                            {
                                Application.Current.Dispatcher.Invoke(() =>
                                {
                                    MainWindow.data.TaskInfos.Remove(task);
                                    MainWindow.RefreshDataGrid();
                                });
                                _channel.BasicAck(ea.DeliveryTag, false);
                                RabbitMQUtil._keys.Remove(taskInfo.Task_Id);
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        LogUtils.log.Error(ex.Message, ex);
                    }
                };
                _channel.BasicConsume(queueName, false, consumer);
            }
            catch (Exception ex)
            {
                LogUtils.log.Error(ex.Message, ex);
            }
        }
    }
}
